using System;
using System.Data;
using System.Data.SqlClient;

namespace Rioshu.Web.ViewStateHandlers
{
    public static class SqlViewstateManager
    {
        public static Guid SaveState(byte[] viewstate)
        {
            using (var connection = SqlConnectionManager.GetConnection()) 
            using (var cmd = new SqlCommand("usp_insertViewState", connection))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@viewstate", SqlDbType.VarBinary, viewstate.Length).Value = viewstate;

                connection.Open();
                var result = (Guid) cmd.ExecuteScalar();
                return result;
            }
        }

        public static byte[] LoadState(Guid id)
        {
            using (var connection = SqlConnectionManager.GetConnection())
            using (var cmd = new SqlCommand("usp_loadViewState", connection)) {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@id", SqlDbType.UniqueIdentifier).Value = id;
                
                connection.Open();
                var result = (byte[]) cmd.ExecuteScalar();
                return result;
            }
        }
    }
}